package com.tjnu.losca.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjnu.losca.mapper.AdviceMapper;
import com.tjnu.losca.pojo.Advice;
import com.tjnu.losca.pojo.Userinfo;
import com.tjnu.losca.service.IAdviceService;
import com.tjnu.losca.service.IUserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 意见表 服务实现类
 * </p>
 *
 * @author losca
 * @since 2022-02-14
 */
@Service
public class AdviceServiceImpl extends ServiceImpl<AdviceMapper, Advice> implements IAdviceService {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    IUserinfoService userinfoService;
    @Autowired
    JavaMailSender mailSender;
    @Override
    public boolean save(String username, String text) {
        QueryWrapper<Userinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Userinfo user = userinfoService.getOne(wrapper);
        Advice advice = new Advice();
        advice.setUserid(user.getUserid());
        advice.setText(text);
        advice.setUsername(user.getName());
        return this.save(advice);
    }

    @Override
    public IPage<Advice> getAll(int pageNum, int pageSize) {
        QueryWrapper<Advice> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        return this.page(new Page<>(pageNum,pageSize),wrapper);
    }

    @Override
    public boolean del(String id) {
        return this.removeById(id);

    }

    @Override
    public boolean reply(String username, String email, String reply) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(email);
            simpleMailMessage.setText(reply);
            simpleMailMessage.setSubject("买买买商城");
            mailSender.send(simpleMailMessage);
            return true;
        } catch (MailException e) {
            e.printStackTrace();
            return false;
        }
    }
}
